package cc.miwuya.community.controller;

import cc.miwuya.common.util.Result;
import cc.miwuya.community.domain.Role;
import cc.miwuya.community.domain.RoleUser;
import cc.miwuya.community.service.RoleService;
import cc.miwuya.community.service.RoleUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author 迷雾森林
 * @Date 2024-02-28 17:50
 * @Desc 角色控制器
 */
@RestController
@RequestMapping("/community/role")
public class RoleController {
    @Resource
    RoleService roleService;
    @Resource
    RoleUserService roleUserService;
    @GetMapping("/list")
    public Result roleList(){
        return Result.success(roleService.list());
    }
    @GetMapping("/userRole/{id}")
    public List<Role> getUserRole(@PathVariable Long id){
        List<Long> list = roleUserService.listObjs(new QueryWrapper<RoleUser>().eq("user_id", id).select("id"));
        List<Role> roles = roleService.list(new QueryWrapper<Role>().in("id", list));
        return roles;
    }
    @PostMapping("/changeRole")
    public Result changeRole(@RequestBody RoleUser roleUser){
        roleUserService.remove(new QueryWrapper<RoleUser>().eq("user_id", roleUser.getUserId()));
        for (Long id : roleUser.getIds()) {
            RoleUser user = new RoleUser();
            user.setId(id);
            user.setUserId(roleUser.getUserId());
            roleUserService.save(user);
        }
        return Result.success();
    }

}
